//------------------------------------------------------------------------------
//  streamreader.cc
//  (C) 2006 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "streamreader.h"

namespace GBase
{

	//------------------------------------------------------------------------------
	/**
	*/
	StreamReader::StreamReader() :
		isOpen(false),
		stream(0),
		deleteStream(true),
		streamWasOpen(false)
	{
		// empty
	}

	//------------------------------------------------------------------------------
	/**
	*/
	StreamReader::~StreamReader()
	{
		checkSlow(!this->IsOpen());
		if (deleteStream && this->stream)
		{
			delete this->stream;
		}
	}

	//------------------------------------------------------------------------------
	/**
		Attaches the reader to a stream. This will imcrement the refcount
		of the stream.
	*/
	void
	StreamReader::SetStream(Stream* s, bool delStream)
	{
		if (this->stream && this->deleteStream)
		{
			delete this->stream;
		}
		this->stream = s;
		this->deleteStream = delStream;
	}

	//------------------------------------------------------------------------------
	/**
		Get pointer to the attached stream. If there is no stream attached,
		an assertion will be thrown. Use HasStream() to determine if a stream
		is attached.
	*/
	Stream* StreamReader::GetStream()
	{
		return this->stream;
	}

	//------------------------------------------------------------------------------
	/**
		Returns true if a stream is attached to the reader.
	*/
	bool
	StreamReader::HasStream() const
	{
		return (this->stream != 0);
	}

	//------------------------------------------------------------------------------
	/**
	*/
	bool
	StreamReader::Eof() const
	{
		checkSlow(this->IsOpen());
		return this->stream->Eof();
	}

	//------------------------------------------------------------------------------
	/**
	*/
	bool
	StreamReader::Open()
	{
		checkSlow(!this->isOpen);
		checkSlow((this->stream != 0));
		checkSlow(this->stream->CanRead());
		if (this->stream->IsOpen())
		{
			checkSlow((this->stream->GetAccessMode() == Stream::ReadAccess) || (this->stream->GetAccessMode() == Stream::ReadWriteAccess));
			this->streamWasOpen = true;
			this->isOpen = true;
		}
		else
		{
			this->streamWasOpen = false;
			this->stream->SetAccessMode(Stream::ReadAccess);
			this->isOpen = this->stream->Open();
		}
		return this->isOpen;
	}

	//------------------------------------------------------------------------------
	/**
	*/
	void
	StreamReader::Close()
	{
		checkSlow(this->isOpen);
		if ((!this->streamWasOpen) && stream->IsOpen())
		{
			this->stream->Close();
		}
		this->isOpen = false;
	}

} // namespace Core
